package com.star95.springbooti18n.common.util;

import com.star95.springbooti18n.common.constants.MessagesEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;

/**
 * 国际化支持工具类
 */
@Component
public class MessageUtils {

    private static MessageSource messageSource;

    @Autowired
    public void setMessageSource(MessageSource messageSource1) {
        messageSource = messageSource1;
    }

    public static String getMessage(String code) {
        return messageSource.getMessage(code, null, LocaleContextHolder.getLocale());
    }

    public static String getMessage(String code, Object... arg) {
        return messageSource.getMessage(code, arg, LocaleContextHolder.getLocale());
    }

    public static String getI18NMessage(MessagesEnum messagesEnum) {
        return getI18NMessage(messagesEnum.getCode(), messagesEnum.getMsg());
    }

    public static String getI18NMessage(String code, String defaultMsg) {
        String msg = getMessage(code);
        if (StringUtils.isEmpty(msg)) {
            return defaultMsg;
        }
        return msg;
    }

    public static String getI18NMessage(String code, String defaultMsg, Object... arg) {
        String msg = getMessage(code, arg);
        if (StringUtils.isEmpty(msg)) {
            MessageFormat format = new MessageFormat(defaultMsg, LocaleContextHolder.getLocale());
            msg = format.format(arg);
        }
        return msg;
    }
}

